package com.css.fxfzmh.util;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

public class FileUploadUtil {

    /**
     * 上传文件工具类
     *
     * @param uploadFile 文件
     * @param fileDir    文件目录名
     * @param request
     * @return
     */
    public static String uploadUtil(MultipartFile uploadFile, String fileDir, HttpServletRequest request) {
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        long size = uploadFile.getSize();
        Long maxfile = 1024*50*1024l;
        if (size>maxfile)
        {
            return "文件超出50M" ;
        }
        String realPath = fileDir;
        System.out.println("文件上传：" + realPath);
        // String format = "/"+sdf.format(new Date());
        File folder = new File(realPath);
        // 是否目录
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        String filePath = "";
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
        try {
            uploadFile.transferTo(new File(folder, newName));
            filePath = fileDir + "/" + newName;
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    public static void download(String path, HttpServletResponse res){
        InputStream fis=null;
        OutputStream toClient=null;
        try {
            //获取下载的路径
            File file=new File(path);
            //获取文件名
            String filename=file.getName();
            //取得文件的后缀名
            String ext=filename.substring(filename.lastIndexOf(".")+1).toUpperCase();
            //以流的形式下载文件
            fis=new BufferedInputStream(new FileInputStream(file));
            System.out.println("文件大小："+fis.available());
            //创建一个和文件一样大小的缓存区
            byte[] buffer=new byte[fis.available()];
            //读取流
            fis.read(buffer);
            //清空首部空白行
            res.reset();
            //设置文件下载后的指定文件名
            res.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("gb2312"),"ISO8859-1"));
            res.addHeader("Content-Length", "" + file.length());
            //response.getOutputStream() 获得字节流，通过该字节流的write(byte[] bytes)可以向response缓冲区中写入字节，再由Tomcat服务器将字节内容组成Http响应返回给浏览器。
            toClient = new BufferedOutputStream(res.getOutputStream());
            res.setContentType("application/octet-stream");
            //将buffer 个字节从指定的 byte 数组写入此输出流。
            toClient.write(buffer);
            //刷新此缓冲的输出流。这迫使所有缓冲的输出字节被写出到底层输出流中。 把缓存区的数据全部写出
            toClient.flush();
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            try {
                //关闭流
                fis.close();
                //关闭缓冲输出流
                toClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
